package com.hj.util;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * redis数据库操作工具类
 *
 * @author haoshen
 * @version 1.0
 */
@SuppressWarnings("all")
@Component
public class RedisUtil {

    private static RedisTemplate<String, String> redisTemplate;

    /* 读取缓存*/
    public static String get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /* 设置缓存*/
    public static boolean set(String key, String value) {
        boolean flag = false;
        try {
            redisTemplate.opsForValue().set(key, value);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /* 设置缓存  过期时间ttl*/
    public static boolean set(String key, String value, long ttl, TimeUnit timeUnit) {
        boolean flag = false;
        try {
            redisTemplate.opsForValue().set(key, value, ttl, timeUnit);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /* 更新缓存 */
    public static boolean getAndSet(String key, String value) {
        boolean flag = false;
        try {
            redisTemplate.opsForValue().getAndSet(key, value);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /* 删除缓存 */
    public static boolean delete(String key) {
        boolean flag = false;
        try {
            redisTemplate.delete(key);
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    @Resource
    public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
        RedisUtil.redisTemplate = redisTemplate;
    }
}
